package com.waijiaojun.tpo.web.admin;

import com.waijiaojun.tpo.entity.Category;
import com.waijiaojun.tpo.entity.Scenario;
import com.waijiaojun.tpo.model.ArticleModel;
import com.waijiaojun.tpo.rest.RestClientException;
import com.waijiaojun.tpo.rest.RestResponse;
import com.waijiaojun.tpo.rest.RestServerException;
import com.waijiaojun.tpo.service.CategoryService;
import com.waijiaojun.tpo.service.ScenarioService;
import com.waijiaojun.tpo.service.UserCategoryService;
import com.waijiaojun.tpo.utils.Constants;
import com.waijiaojun.tpo.utils.JsonUtil;
import com.waijiaojun.tpo.vo.BootstrapTableDataResponse;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.support.RedirectAttributes;

import java.util.List;

/**
 * Created with IntelliJ IDEA.
 * User: xvitcoder
 * Date: 12/20/12
 * Time: 5:27 PM
 */
@Controller
@RequestMapping("/admin")
public class AdminCategoryController {

    private static Logger logger = LoggerFactory.getLogger(AdminCategoryController.class);
    @Autowired
    private UserCategoryService userCategoryService;
    @Autowired
    private ScenarioService scenarioService;
    @Autowired
    private CategoryService categoryService;

    @RequestMapping
    public String indexPage() {
        logger.info("indexPage-------------------");
        return "admin/category-list";
    }


    @RequestMapping("category/list")
    public String categoryList() {
        logger.info("categoryList-------------------");
        return "admin/category-list";
    }

    @RequestMapping("category/list/data")
    @ResponseBody
    public BootstrapTableDataResponse<Category> categoryListData(@RequestParam(value = "order", required = false, defaultValue = "ASC") String order,
                                                                 @RequestParam(value = "sort", required = false, defaultValue = "id") String sort,
                                                                 @RequestParam("offset") Integer offset,
                                                                 @RequestParam("limit") Integer limit,
                                                                 @RequestParam(value = "search", required = false, defaultValue = "") String search) {
        logger.info(Constants.prefix_in + "sort=" + sort + ", order=" + order + ", offset=" + offset + ", limit=" + limit + ", search=" + search);
        BootstrapTableDataResponse<Category> list = userCategoryService.findAll(offset, limit, search, order, sort);
        //打印出参
        logger.info(Constants.prefix_out + JsonUtil.toJson(list));
        return list;
    }

    @RequestMapping("category/add")
    public String categoryAdd(Model model) {
        model.addAttribute("category", new Category());
        return "admin/category-add";
    }

    @RequestMapping(value = "category/addSave", method = {RequestMethod.POST})
    public String categoryAddSave(@ModelAttribute("category") Category category, Model model, RedirectAttributes redirectAttributes) {
        logger.info(Constants.prefix_in + JsonUtil.toJson(category));
        try {
            categoryService.save(category);
            redirectAttributes.addFlashAttribute("successMessage", "保存成功");
            return "redirect:/admin/category/edit?id=" + category.getId();
        } catch (RestClientException e) {
            logger.error(e.getMessage(), e);
            model.addAttribute("errorMessage", "保存失败");
            return "admin/category-add";
        } catch (RestServerException e) {
            logger.error(e.getMessage(), e);
            model.addAttribute("errorMessage", "保存失败");
            return "admin/category-add";
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            model.addAttribute("errorMessage", "保存失败");
            return "admin/category-add";
        }
    }

    @RequestMapping("category/edit")
    public String categoryEdit(@RequestParam(required = false, defaultValue = "0") Long id, Model model) {
        logger.info(Constants.prefix_in + "id=" + id);
        Category category = categoryService.findById(id);
        if (category == null) {
            category = new Category();
        }
        model.addAttribute("category", category);
        return "admin/category-edit";
    }

    @RequestMapping(value = "category/editSave", method = {RequestMethod.POST})
    public String categoryEditSave(@ModelAttribute("category") Category category, Model model) {
        try {
            logger.info(Constants.prefix_in + JsonUtil.toJson(category));//打印入参
            categoryService.save(category);
            Category category1 = categoryService.findById(category.getId());
            model.addAttribute("category", category1);
            model.addAttribute("successMessage", "保存成功");
        } catch (RestClientException e) {
            logger.error(e.getMessage(), e);
            model.addAttribute("errorMessage", "保存失败");
        } catch (RestServerException e) {
            logger.error(e.getMessage(), e);
            model.addAttribute("errorMessage", "保存失败");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            model.addAttribute("errorMessage", "保存失败");
        }
        return "admin/category-edit";
    }

    @RequestMapping("category/editShortcutSave")
    @ResponseBody
    public RestResponse categoryEditShortcutSave(Category category) {
        RestResponse restResponse = null;
        try {
            logger.info(Constants.prefix_in + JsonUtil.toJson(category));//打印入参

            userCategoryService.updateCategory(category);
            restResponse = RestResponse.getSuccessResponse();
        } catch (RestClientException e) {
            logger.error(e.getMessage(), e);
            restResponse = RestResponse.getClientErrorResponse(e.getMessage());
        } catch (RestServerException e) {
            logger.error(e.getMessage(), e);
            restResponse = RestResponse.getServerErrorResponse(e.getMessage());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            restResponse = RestResponse.getServerErrorResponse(e.getMessage());
        }
        //打印出参
        logger.info(Constants.prefix_out + JsonUtil.toJson(restResponse));
        return restResponse;
    }

    @RequestMapping("category/delete/{id}")
    @ResponseBody
    public RestResponse categoryDelete(@PathVariable Long id) {
        RestResponse restResponse = null;
        try {
            logger.info(Constants.prefix_in + "id=" + id);//打印入参

            userCategoryService.deleteCategory(id);
            restResponse = RestResponse.getSuccessResponse();
        } catch (RestClientException e) {
            logger.error(e.getMessage(), e);
            restResponse = RestResponse.getClientErrorResponse(e.getMessage());
        } catch (RestServerException e) {
            logger.error(e.getMessage(), e);
            restResponse = RestResponse.getServerErrorResponse(e.getMessage());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            restResponse = RestResponse.getServerErrorResponse(e.getMessage());
        }
        //打印出参
        logger.info(Constants.prefix_out + JsonUtil.toJson(restResponse));
        return restResponse;
    }


    @RequestMapping("article/list")
    public String carticleList(Model model) {
        List<Category> categoryList = categoryService.findAll();

        model.addAttribute("categoryList", categoryList);
        return "admin/article-list";
    }

    @RequestMapping("article/list/data")
    @ResponseBody
    public BootstrapTableDataResponse<Scenario> articleListData(@RequestParam(value = "order", required = false, defaultValue = "ASC") String order,
                                                                @RequestParam(value = "sort", required = false, defaultValue = "id") String sort,
                                                                @RequestParam(value = "offset", required = false, defaultValue = "0") Integer offset,
                                                                @RequestParam(value = "limit", required = false, defaultValue = "50") Integer limit,
                                                                @RequestParam(value = "categoryId", required = false, defaultValue = "") String categoryId,
                                                                @RequestParam(value = "search", required = false) String search) {
        logger.info(Constants.prefix_in + "sort=" + sort + ", order=" + order + ", offset=" + offset + ", limit=" + limit + ", categoryId=" + categoryId+ ", search=" + search);
        if (StringUtils.isBlank(categoryId)) {
            categoryId = null;
        }
        if (StringUtils.isBlank(search)) {
            search = null;
        }
        BootstrapTableDataResponse<Scenario> list = scenarioService.findAll(offset, limit, categoryId, order, sort,search);
        //打印出参
        logger.info(Constants.prefix_out + JsonUtil.toJson(list));
        return list;
    }

    @RequestMapping("article/edit")
    public String articleEdit(@RequestParam(required = false, defaultValue = "0") Long id, Model model) {
        logger.info(Constants.prefix_in + "id=" + id);
        Scenario scenario = scenarioService.findById(id);
        if (scenario == null) {
            scenario = new Scenario();
        }
        if (scenario.getCategoryId() == null) {
            scenario.setCategoryId(0L);
        }
        List<Category> categoryList = categoryService.findAll();

        model.addAttribute("categoryList", categoryList);
        model.addAttribute("article", scenario);
        return "admin/article-edit";
    }

    @RequestMapping(value = "article/save", method = {RequestMethod.POST})
    public String articleSave(@ModelAttribute("article") Scenario article, Model model) {
        logger.info(Constants.prefix_in + JsonUtil.toJson(article));
        try {
            Scenario scenario = scenarioService.save(article);
            model.addAttribute("successMessage", "保存成功");
        } catch (RestClientException e) {
            logger.error(e.getMessage(), e);
            model.addAttribute("errorMessage", "保存失败");
        } catch (RestServerException e) {
            logger.error(e.getMessage(), e);
            model.addAttribute("errorMessage", "保存失败");
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            model.addAttribute("errorMessage", "保存失败");
        }

        article = scenarioService.findById(article.getId());
        List<Category> categoryList = categoryService.findAll();

        model.addAttribute("article", article);
        model.addAttribute("categoryList", categoryList);
        return "admin/article-edit";
    }

    @RequestMapping("article/delete/{id}")
    @ResponseBody
    public RestResponse articleDelete(@PathVariable Long id) {
        RestResponse restResponse = null;
        try {
            logger.info(Constants.prefix_in + "id=" + id);//打印入参

            scenarioService.delete(id);
            restResponse = RestResponse.getSuccessResponse();
        } catch (RestClientException e) {
            logger.error(e.getMessage(), e);
            restResponse = RestResponse.getClientErrorResponse(e.getMessage());
        } catch (RestServerException e) {
            logger.error(e.getMessage(), e);
            restResponse = RestResponse.getServerErrorResponse(e.getMessage());
        } catch (Exception e) {
            logger.error(e.getMessage(), e);
            restResponse = RestResponse.getServerErrorResponse(e.getMessage());
        }
        //打印出参
        logger.info(Constants.prefix_out + JsonUtil.toJson(restResponse));
        return restResponse;
    }

}
